package com.example.netlib.activity;

import androidx.annotation.Nullable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.netlib.ActionUrl;
import com.example.netlib.BaseHttpResultBean;
import com.example.netlib.DefaultFileUploadHttpResultHandler;
import com.example.netlib.DefaultHttpResultHandler;
import com.example.netlib.R;
import com.example.netlib.netwrapper.LocalHttpClientHolder;
import com.example.netlib.util.tip.SystemDialogFactory;
import com.szlanyou.thirdsdk.retrofit.client.RequestType;
import com.szlanyou.thirdsdk.retrofit.file.upload.UploadFileWrapper;
import com.szlanyou.thirdsdk.retrofit.util.MyLogUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.SelectionSpec;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传测试界面
 */
public class UploadFileActivity extends BaseActivity {
    private final int REQUEST_CODE_SINGLE_FILE_UPLOAD = 100;
    private final int REQUEST_CODE_MANY_FILE_UPLOAD = 200;
    private DefaultFileUploadHttpResultHandler<BaseHttpResultBean>  fileUploadHttpResultHandler = new DefaultFileUploadHttpResultHandler<BaseHttpResultBean>() {
        @Override
        public void onStart(String requestPageFlag,String requestCode) {
            super.onStart(requestPageFlag,requestCode);
            progressDialog.show();
        }

        @Override
        public void onSuccess(String requestPageFlag,String requestCode, BaseHttpResultBean successBean) {
            super.onSuccess(requestPageFlag,requestCode, successBean);
            Toast.makeText(UploadFileActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(String requestPageFlag,String requestCode, Throwable e) {
            super.onError(requestPageFlag,requestCode, e);
            Toast.makeText(UploadFileActivity.this, "上传失败 " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onRequestProgress(String url, long bytesWritten, long contentLength) {
            super.onRequestProgress(url, bytesWritten, contentLength);
            int progress = (int) (bytesWritten * 100.0 / contentLength);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressDialog.setProgress(progress);
                }
            });
        }

        @Override
        public void onComplete(boolean causeByError) {
            super.onComplete(causeByError);
            progressDialog.dismiss();
            SystemDialogFactory.releaseProgressDialog();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_file);
    }


    /**
     * 单文件上传
     *
     * @param view
     */
    public void singleFileUploadTest(View view) {
        Matisse.from(this)
//                .choose(MimeType.of(MimeType.PNG, MimeType.JPEG))     //图片选择
                .choose(MimeType.ofAll())
                .capture(false)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .imageEngine(SelectionSpec.getInstance().imageEngine)
                .forResult(REQUEST_CODE_SINGLE_FILE_UPLOAD);
    }


    /**
     * 批量上传
     *
     * @param view
     */
    public void manyFileUploadTest(View view) {
        Matisse.from(this)
//                .choose(MimeType.of(MimeType.PNG, MimeType.JPEG))    //图片选择
                .choose(MimeType.ofAll())
                .capture(false)
                .maxSelectable(2)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .imageEngine(SelectionSpec.getInstance().imageEngine)
                .forResult(REQUEST_CODE_MANY_FILE_UPLOAD);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SINGLE_FILE_UPLOAD && resultCode == Activity.RESULT_OK) {
            List<String> mSelectedPathList = Matisse.obtainPathResult(data);
            if (mSelectedPathList != null && mSelectedPathList.size() == 1) {
                String mSelectedPath = mSelectedPathList.get(0);
                Log.d("TAG", "选择文件: " + mSelectedPath);

                Map<String, Object> params = new HashMap<>();
                params.put("key1", "value1");
                UploadFileWrapper uploadFileWrapper = new UploadFileWrapper(
                        new File(mSelectedPath), "file"
                );
                ProgressDialog progressDialog = SystemDialogFactory.getProgressDialog(this,"上传中...");
                progressDialog.setCancelable(true);
                progressDialog.setCanceledOnTouchOutside(true);
                fileUploadHttpResultHandler.setProgressDialog(progressDialog);

                LocalHttpClientHolder.getInstance().getHttpClient().newRequestBuilder().type(RequestType.FILE_UPLOAD)
                        .url(LocalHttpClientHolder.getInstance().getActionUrl().UPLOAD_SINGLE_FILE)
                        .autoShowLoading(true)
                        .setParams(params)
                        .addHeader("privateHeaderKey1","privateHeaderValue1")
                        .addHeader("privateHeaderKey2",999999)
                        .requestCode(String.valueOf(requestCode))
                        .httpResultHandler(fileUploadHttpResultHandler)
                        .setUploadFile(uploadFileWrapper)
                        .request();

            }
        } else if (requestCode == REQUEST_CODE_MANY_FILE_UPLOAD && resultCode == Activity.RESULT_OK) {
            List<String> mSelectedPathList = Matisse.obtainPathResult(data);
            List<UploadFileWrapper> uploadFileWrapperList = new ArrayList<>();
            for (String item : mSelectedPathList) {
                Log.d("TAG", "选择文件: " + item);
                uploadFileWrapperList.add(new UploadFileWrapper(new File(item), "file"));
            }
            Map<String, Object> params = new HashMap<>();
            params.put("key1", "value1");

            ProgressDialog progressDialog = SystemDialogFactory.getProgressDialog(this,"上传中...");
            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(true);

            fileUploadHttpResultHandler.setProgressDialog(progressDialog);

            LocalHttpClientHolder.getInstance().getHttpClient().newRequestBuilder().type(RequestType.FILE_UPLOAD)
                    .url(LocalHttpClientHolder.getInstance().getActionUrl().UPLOAD_MANY_FILE)
                    .autoShowLoading(false)
                    .setParams(params)
                    .addHeader("privateHeaderKey1","privateHeaderValue1")
                    .addHeader("privateHeaderKey2",999999)
                    .requestCode(String.valueOf(requestCode))
                    .httpResultHandler(fileUploadHttpResultHandler)
                    .setUploadFile(uploadFileWrapperList)
                    .request();

        }
    }

    public void cancelSingleFileUploadTest(View view) {
        LocalHttpClientHolder.getInstance().getHttpClient().cancel(String.valueOf(REQUEST_CODE_SINGLE_FILE_UPLOAD));
    }

    public void cancelManyFileUploadTest(View view) {
        LocalHttpClientHolder.getInstance().getHttpClient().cancel(String.valueOf(REQUEST_CODE_MANY_FILE_UPLOAD));
    }

}